﻿using BlazorComponent;
using ImoviesBlazor.Shared.Dtos;
using ImoviesBlazor.Shared.Utils;
using System.Net.Http.Json;
using System.Text.Json;

namespace ImoviesBlazor.Client.Pages.admin
{
    public partial class VLmanage
    {

        /// <summary>
        /// 表格展示用类
        /// </summary>
        public class TableViewModel
        {
            public uint Id { get; set; }
            public string Name { get; set; }
            public string Url { get; set; }
            public string RealUrl { get; set; }

            public TableViewModel() { }
        }

        /// <summary>
        /// 视频类型选择类
        /// </summary>
        public class VcateSelectItem
        {
            public string Label { get; set; }
            public string Value { get; set; }

            public VcateSelectItem(string label, string value)
            {
                this.Label = label;
                this.Value = value;
            }
        }


        /// <summary>
        /// 视频选择
        /// </summary>
        public class VideoSelectItem
        {
            public string Name { get; set; }
            public string Id { get; set; }

            public VideoSelectItem()
            {

            }

            public VideoSelectItem(string name, string id)
            {
                this.Name = name;
                this.Id = id;
            }
        }

        /// <summary>
        /// 表头定义
        /// </summary>
        public List<DataTableHeader<TableViewModel>> headers = new List<DataTableHeader<TableViewModel>>
        {
            new (){ Text= "Id", Value= nameof(TableViewModel.Id),Sortable=false,Width="80px",Align="center"},
            new (){ Text= "名称", Value= nameof(TableViewModel.Name),Width="200px",Align="center"},
            new (){ Text= "地址", Value= nameof(TableViewModel.Url),Sortable=false,Width="400px", Align="center"},
            new (){ Text= "播放", Value= nameof(TableViewModel.RealUrl),Sortable=false,Width="400px",Align="center"},
            new (){ Text= "操作", Value= "actions",Sortable=false,Width="100px",Align="center" }
        };

        /// <summary>
        /// 显示到表格的视频数据
        /// </summary>
        public List<TableViewModel> vlinkList = new List<TableViewModel>();

        /// <summary>
        /// 被选中的视频分类
        /// </summary>
        public string selectedVideoCate = null;

        /// <summary>
        /// 被选中的视频
        /// </summary>
        public string selectedVideoId = null;

        public bool _dialogEdit;
        public bool _dialogAdd;
        public bool _dialogDelete;

        /// <summary>
        /// 分类下拉框内容
        /// </summary>
        List<VcateSelectItem> vcateSelectItems = new()
        {
            new VcateSelectItem("电视剧", "电视剧"),
            new VcateSelectItem("电影", "电影"),
            new VcateSelectItem("动漫", "动漫")
        };

        /// <summary>
        /// 视频下拉框内容
        /// </summary>
        List<VideoSelectItem> videoSelectItems = new List<VideoSelectItem>();


        public TableViewModel _editedItem = new TableViewModel();
        public TableViewModel _addItem = new TableViewModel();

        /// <summary>
        /// 关闭对话框
        /// </summary>
        public void Close()
        {
            _dialogEdit = false;
            _dialogAdd = false;
            _editedItem = new TableViewModel();
            _addItem = new TableViewModel();
        }

        /// <summary>
        /// 显示添加表单
        /// </summary>
        public void ShowAddForm()
        {
            if (string.IsNullOrEmpty(selectedVideoCate) || string.IsNullOrEmpty(selectedVideoId))
            {
                return;
            }
            _dialogAdd = true;
        }

        /// <summary>
        /// 提交编辑
        /// </summary>
        public async Task SubmitEdit()
        {
            HttpResponseMessage res;
            switch (selectedVideoCate)
            {
                case "电视剧":
                    TeleplayVlinkForUpdateDto tdata = new TeleplayVlinkForUpdateDto
                    {
                        Id = _editedItem.Id,
                        TeleplayId = selectedVideoId,
                        Name = _editedItem.Name,
                        Url = _editedItem.Url,
                        RealUrl = _editedItem.RealUrl,
                    };
                    res = await HttpClient.PutAsJsonAsync<TeleplayVlinkForUpdateDto>("/api/TeleplayVlink", tdata);
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogEdit = false;
                        _editedItem = new TableViewModel();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;

                case "电影":
                    MovieVlinkForUpdateDto mdata = new MovieVlinkForUpdateDto
                    {
                        Id = _editedItem.Id,
                        MovieId = selectedVideoId,
                        Name = _editedItem.Name,
                        Url = _editedItem.Url,

                    };
                    res = await HttpClient.PutAsJsonAsync<MovieVlinkForUpdateDto>("/api/MovieVlink", mdata);
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogEdit = false;
                        _editedItem = new TableViewModel();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;

                case "动漫":
                    AnimationVlinkForUpdateDto adata = new AnimationVlinkForUpdateDto
                    {
                        Id = _editedItem.Id,
                        AnimationId = selectedVideoId,
                        Name = _editedItem.Name,
                        Url = _editedItem.Url,
                    };
                    res = await HttpClient.PutAsJsonAsync<AnimationVlinkForUpdateDto>("/api/AnimationVlink", adata);
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogEdit = false;
                        _editedItem = new TableViewModel();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 提交添加
        /// </summary>
        public async Task SubmitAddAsync()
        {
            HttpResponseMessage res;
            switch (selectedVideoCate)
            {
                case "电视剧":
                    TeleplayVlinkForCreateDto tdata = new TeleplayVlinkForCreateDto
                    {
                        TeleplayId = selectedVideoId,
                        Name = _addItem.Name,
                        Url = _addItem.Url,
                        RealUrl = _addItem.RealUrl,
                    };
                    res = await HttpClient.PostAsJsonAsync<TeleplayVlinkForCreateDto>("/api/TeleplayVlink", tdata);
                    if (res.IsSuccessStatusCode)
                    {
                        _dialogAdd = false;
                        _addItem = new TableViewModel();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                case "电影":
                    MovieVlinkForCreateDto mdata = new MovieVlinkForCreateDto
                    {
                        MovieId = selectedVideoId,
                        Name = _addItem.Name,
                        Url = _addItem.Url,
                        RealUrl = _addItem.RealUrl,
                    };
                    res = await HttpClient.PostAsJsonAsync<MovieVlinkForCreateDto>("/api/MovieVlink", mdata);
                    if (res.IsSuccessStatusCode)
                    {
                        _dialogAdd = false;
                        _addItem = new TableViewModel();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                case "动漫":
                    AnimationVlinkForCreateDto adata = new AnimationVlinkForCreateDto
                    {
                        AnimationId = selectedVideoId,
                        Name = _addItem.Name,
                        Url = _addItem.Url,
                        RealUrl = _addItem.RealUrl,
                    };
                    res = await HttpClient.PostAsJsonAsync<AnimationVlinkForCreateDto>("/api/AnimationVlink", adata);
                    if (res.IsSuccessStatusCode)
                    {
                        _dialogAdd = false;
                        _addItem = new TableViewModel();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                default:
                    break;
            }

        }

        /// <summary>
        /// 编辑按钮点击
        /// </summary>
        /// <param name="item"></param>
        public void EditItem(TableViewModel item)
        {
            _editedItem = item;
            _dialogEdit = true;
        }

        private uint awaitDelId;
        /// <summary>
        /// 删除按钮点击
        /// </summary>
        /// <param name="item"></param>
        public void DeleteItem(uint id)
        {
            awaitDelId = id;
            _dialogDelete = true;
        }

        /// <summary>
        /// 提交删除
        /// </summary>
        public async Task DeleteItemConfirmAsync()
        {
            HttpResponseMessage res;
            switch (selectedVideoCate)
            {
                case "电视剧":
                    res = await HttpClient.DeleteAsync($"/api/TeleplayVlink/{awaitDelId}");
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogDelete = false;
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                case "电影":
                    res = await HttpClient.DeleteAsync($"/api/MovieVlink/{awaitDelId}");
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogDelete = false;
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                case "动漫":
                    res = await HttpClient.DeleteAsync($"/api/AnimationVlink/{awaitDelId}");
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogDelete = false;
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                default:
                    break;
            }

            CloseDelete();
        }

        /// <summary>
        /// 关闭删除对话框
        /// </summary>
        public void CloseDelete()
        {
            awaitDelId = 0;
            _dialogDelete = false;
            _editedItem = new TableViewModel();
        }


        /// <summary>
        /// 视频类型选择改变
        /// </summary>
        /// <returns></returns>
        public async Task VcateSelectedChange(string value)
        {
            selectedVideoCate = value;
            selectedVideoId = null;
            switch (value)
            {
                case "电视剧":
                    videoSelectItems = await GetTeleplays();
                    break;
                case "电影":
                    videoSelectItems = await GetMovies();
                    break;
                case "动漫":
                    videoSelectItems = await GetAnimations();
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 视频类型选择下拉框清空事件
        /// </summary>
        public void ClearVcate()
        {
            selectedVideoCate = null;
            vlinkList.Clear();
            videoSelectItems.Clear();
        }




        /// <summary>
        /// 获取全部电视剧
        /// </summary>
        /// <returns></returns>
        private async Task<List<VideoSelectItem>> GetTeleplays()
        {
            var resp = await HttpClient.GetAsync("api/teleplay/all");
            var resData = JsonSerializer.Deserialize<List<VideoSelectItem>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });

            return resData ?? new List<VideoSelectItem>();
        }

        /// <summary>
        /// 获取全部电影
        /// </summary>
        /// <returns></returns>
        private async Task<List<VideoSelectItem>> GetMovies()
        {
            var resp = await HttpClient.GetAsync("api/movie/all");
            var resData = JsonSerializer.Deserialize<List<VideoSelectItem>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });

            return resData ?? new List<VideoSelectItem>();
        }

        /// <summary>
        /// 获取全部动漫
        /// </summary>
        /// <returns></returns>
        private async Task<List<VideoSelectItem>> GetAnimations()
        {
            var resp = await HttpClient.GetAsync("api/animation/all");
            var resData = JsonSerializer.Deserialize<List<VideoSelectItem>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });

            return resData ?? new List<VideoSelectItem>();
        }


        /// <summary>
        /// 视频被选中
        /// </summary>
        /// <param name="vid"></param>
        /// <returns></returns>
        public async Task VideoSelectedChange(string vid)
        {
            if (string.IsNullOrEmpty(selectedVideoCate))
            {
                return;
            }
            selectedVideoId = vid;
            switch (selectedVideoCate)
            {
                case "电视剧":
                    vlinkList = await GetTeleplayLinks(vid);
                    break;
                case "电影":
                    vlinkList = await GetMovieLinks(vid);
                    break;
                case "动漫":
                    vlinkList = await GetAnimationLinks(vid);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 视频类型选择下拉框清空事件
        /// </summary>
        public void ClearVideo()
        {
            selectedVideoId = null;
            videoSelectItems.Clear();
            vlinkList.Clear();
        }

        /// <summary>
        /// 获取某电视剧的播放链接
        /// </summary>
        /// <param name="vid">id</param>
        /// <returns></returns>
        private async Task<List<TableViewModel>> GetTeleplayLinks(string vid)
        {
            var resp = await HttpClient.GetAsync($"api/teleplay/vlist/{vid}");
            var resData = JsonSerializer.Deserialize<List<TableViewModel>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });

            return resData ?? new List<TableViewModel>();
        }


        /// <summary>
        /// 获取某电影的播放链接
        /// </summary>
        /// <param name="vid">id</param>
        /// <returns></returns>
        private async Task<List<TableViewModel>> GetMovieLinks(string vid)
        {
            var resp = await HttpClient.GetAsync($"api/movie/vlist/{vid}");
            var resData = JsonSerializer.Deserialize<List<TableViewModel>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });

            return resData ?? new List<TableViewModel>();
        }


        /// <summary>
        /// 获取某动漫的播放链接
        /// </summary>
        /// <param name="vid">id</param>
        /// <returns></returns>
        private async Task<List<TableViewModel>> GetAnimationLinks(string vid)
        {
            var resp = await HttpClient.GetAsync($"api/animation/vlist/{vid}");
            var resData = JsonSerializer.Deserialize<List<TableViewModel>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });

            return resData ?? new List<TableViewModel>();
        }

    }
}
